package com.yunyan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyan.entity.HistoryData;
import com.yunyan.entity.SchoolData;
import com.yunyan.req.MajorParam;
import com.yunyan.req.PageReq;
import com.yunyan.service.HistoryService;
import com.yunyan.service.MajorService;
import com.yunyan.service.SchoolService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MajorServiceImpl implements MajorService {


    @Resource
    private HistoryService historyService;

    @Resource
    private SchoolService schoolService;

    @Override
    public IPage<HistoryData> pageQuery(PageReq req, MajorParam param) {
        Page<HistoryData> resp = historyService.page(new Page<>(req.getPage(), req.getSize()),
                new QueryWrapper<HistoryData>().select("distinct college_name, id,  professor_name, lower_score, level")
                        .eq(!StringUtils.isEmpty(param.getLevel()), "level", param.getLevel())
                        .eq("year", 2023)
                        .like(!StringUtils.isEmpty(param.getName()), "professor_name", param.getName())
                        .orderByDesc("lower_score")
        );
        List<HistoryData> records = resp.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return resp;
        }

        List<String> nameList = records.stream().map(HistoryData::getCollegeName).collect(Collectors.toList());

        List<SchoolData> schoolDataList = schoolService.listByName(nameList);

        Map<String, SchoolData> collect = schoolDataList.stream().collect(Collectors.toMap(SchoolData::getName, x -> x));

        for (HistoryData record : records) {
            SchoolData schoolData = collect.get(record.getCollegeName());
            if (schoolData != null) {
               record.setSchoolData(schoolData);
            }
        }
        records.sort((o1, o2) -> Integer.parseInt(o2.getLowerScore()) - Integer.parseInt(o1.getLowerScore()));
        resp.setRecords(records);
        return resp;
    }

    @Override
    public List<HistoryData> listByName(String name) {
        return historyService.list(new LambdaQueryWrapper<HistoryData>()
                .eq(HistoryData::getYear, 2023)
                .eq(HistoryData::getCollegeName, name)
        );
    }
}

